package com.xh.bussiness.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xh.bussiness.permission.bean.dto.UserAreaDto;
import com.xh.bussiness.permission.bean.request.SaveUserAreaRequest;
import com.xh.bussiness.permission.dao.UserAreaMapper;
import com.xh.bussiness.permission.model.UserArea;
import com.xh.bussiness.permission.service.IUserAreaService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2020/3/3
 */
@Service
public class UserAreaServiceImpl extends BaseServiceImpl<UserAreaMapper, UserArea> implements IUserAreaService {

    @Override
    public void saveUserArea(SaveUserAreaRequest request) {
        this.dao.deleteByUserId(request.getUserId());
        List<UserArea> data = new ArrayList<>();
        if (!CollectionUtils.isEmpty(request.getAreas())) {
            for (UserAreaDto userAreaDto : request.getAreas()) {
                UserArea userArea = new UserArea();
                BeanUtils.copyProperties(userAreaDto, userArea);
                userArea.setUserId(request.getUserId());
                data.add(userArea);
            }
            this.batchInsert(data);
        }
    }

    @Override
    public List<UserArea> queryByUserId(String userId, Integer grade) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        if (grade != null) {
            qw.eq("grade", grade);
        }
        return this.dao.selectList(qw);
    }

    private List<UserArea> rootList; // 根节点对象存放到这里

    private List<UserArea> bodyList; // 其他节点存放到这里，可以包含根节点

    @Override
    public List<UserArea> queryAreaTree(String userId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        List<UserArea> list = this.dao.selectList(qw);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        rootList = list.stream().filter(item -> item.getGrade().equals(2)).collect(Collectors.toList());
        bodyList = list.stream().filter(item -> !item.getGrade().equals(2)).collect(Collectors.toList());
        List<UserArea> tree = getTree();
        return tree;
    }

    public List<UserArea> getTree() { // 调用的方法入口
        if (bodyList != null && !bodyList.isEmpty()) {
            // 声明一个map，用来过滤已操作过的数据
            Map<Integer, Integer> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return null;
    }

    public void getChild(UserArea beanTree, Map<Integer, Integer> map) {
        List<UserArea> childList = Lists.newArrayList();
        bodyList.stream().filter(c -> !map.containsKey(c.getAreaId())).filter(c -> c.getParentId().equals(beanTree.getAreaId()))
                .forEach(c -> {
                    map.put(c.getAreaId(), c.getParentId());
                    getChild(c, map);
                    childList.add(c);
                });
        beanTree.setChildren(childList);
    }

}
